using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Sfd.Services.Synchronizers;

namespace Sfd.Services
{
    public class Filter
    {
        public Filter()
        {
            ExcludeFoldersPattern = Properties.Settings.Default.DefaultExcludedFoldersPattern;
            ExcludeFilesPattern = Properties.Settings.Default.DefaultExcludedFilesPattern;
            FileMaxSize = Properties.Settings.Default.DefaultFileMaxSize * 1024;
        }

        private string _excludeFoldersPattern;
        private Regex _folderRegex;
        private string _excludeFilesPattern;
        private Regex _fileRegex;

        /// <summary>
        /// Pattern d'exclusion des dossiers
        /// </summary>
        public string ExcludeFoldersPattern
        {
            get { return _excludeFoldersPattern; }
            private set
            {
                _excludeFoldersPattern = value;
                _folderRegex = !string.IsNullOrEmpty(value) ? new Regex(value) : null;
            }
        }
        
        /// <summary>
        /// Pattern d'exclusion des fichiers
        /// </summary>
        public string ExcludeFilesPattern
        {
            get { return _excludeFilesPattern; }
            private set
            {
                _excludeFilesPattern = value;
                _fileRegex = !string.IsNullOrEmpty(value) ? new Regex(value) : null;
            }
        }
        
        /// <summary>
        /// Taille maximale d'un fichier
        /// </summary>
        public long FileMaxSize { get; set; }

        public bool IsMatch(SyncItem syncItem)
        {
            // match le nom du dossier ?
            if (_folderRegex != null)
            {
                var parentFolders =
                    Path.GetDirectoryName(syncItem.Key).Split(new[] { @"\" }, StringSplitOptions.RemoveEmptyEntries).Select(
                        folder => folder.ToLower());

                foreach (string folder in parentFolders)
                {
                    if (_folderRegex.IsMatch(folder))
                        return true;
                }
            }

            // match le nom du fichier ?
            if (_fileRegex != null)
            {
                var singleFileName = Path.GetFileName(syncItem.Key);

                if (_fileRegex.IsMatch(singleFileName))
                    return true;
            }

            // match la taille ?
            return syncItem.Length > FileMaxSize;
        }
    }
}